package com.educate.service.impl;

import com.educate.common.lang.Const;
import com.educate.dao.UserDao;
import com.educate.pojo.User;
import com.educate.service.UserService;
import com.educate.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yjj
 * @date 2021/11/7
 * @description:  UserServiceImp
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 用户Info
     * @param username
     * @return userInfo
     */
    @Override
    public User getUserInfoByUsername(String username) {
        User userInfo = userDao.getUserInfoByUsername(username);
        return userInfo;
    }

    /**
     * 查询账号相关权限
     * @param userId
     * @return authority
     */
    @Override
    public String getUserAuthorityInfo(Long userId) {
        String authority = "";
        String redisKey = "GrantedAuthority" + userId;  //redis key
        //判断redis是否有缓存
        if(redisUtil.hasKey(redisKey)){
            authority = (String) redisUtil.get(redisKey);
        } else {
            List<String> userRoleCode = userDao.getUserRoleCodeById(userId);
            if(userRoleCode.size() > 0){
                authority = userRoleCode.stream().map(v -> "ROLE_" + v).collect(Collectors.joining(","));
            }
            authority.concat(".");
            List<String> userPerms = userDao.getUserPermsById(userId);
            if(userPerms.size() > 0){
                String str = userPerms.stream().collect(Collectors.joining(","));
                authority += str;
            }
            redisUtil.set(redisKey,authority, Const.AUTH_TIME);
        }
        return authority;
    }
    /**
     * 注册
     * @param username
     * @param password
     * @return  flag
     */

    @Transactional
    @Override
    public int registerNewUser(String username, String password) {
        password = bCryptPasswordEncoder.encode(password);
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAvatar(Const.DEFAULT_AVATAR);
        int flag = userDao.register(user);
        userDao.setNewUserRole(user.getId(),2L);
        return flag;
    }

}
